package client.demo;

import bean.DemoProtocol;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 编写一个 main() 方法来启动客户端。
 */
public class SimpleChatClient extends Thread {
    public static void main(String[] args) throws Exception {
//        String host = "123.57.161.210";
        String host = "127.0.0.1";

        for (int i = 0; i < 12; i++) {
            new SimpleChatClient(host, 18098, (byte) i).start();
        }

    }

    private final String host;
    private final int port;
    private final byte id;


    public SimpleChatClient(String host, int port, byte id) {
        this.host = host;
        this.port = port;
        this.id = id;
    }

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new SimpleChatClientInitializer());
            Channel channel = bootstrap.connect(host, port).sync().channel();
            //BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

            while (true) {
                Thread.sleep(1000);

//                for (int i=0;i<b.length;i++){
//                    System.out.print(byteTo16(b[i])+ " ");
//                }
//                System.out.println();
                for (int i = 0; i < 5; i++) {
//                    byte[] b = new byte[]{(byte) 0xF0, id, (byte) i};
                    DemoProtocol protocol = new DemoProtocol();
                    protocol.setHead_data(1);
                    protocol.setContentLength(1);
                    protocol.setContent(new byte[]{(byte) i});
                    ChannelFuture future = channel.writeAndFlush(protocol);
//                    future.addListener(future1 -> System.out.println("==>" + future.isSuccess()));

//                    Thread.sleep(1000);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

    public static String byteTo16(byte bt) {
        String[] strHex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        String resStr = "";
        int low = (bt & 15);
        int high = bt >> 4 & 15;
        resStr = strHex[high] + strHex[low];
        return resStr;
    }
}
